#include "Analysis.h"
#include <Arduino.h>
#include <ArduinoJson.h>

void Reiceve(SoftwareSerial& mySerial) {
  while (mySerial.available())  //获取从软串口读取有效的字节数
  {
    char a = mySerial.read();
    Serial.print(a);
    delay(1);
  }
}



#define MAX_INPUT_LENGTH 390
char json[MAX_INPUT_LENGTH] = { 0 };
void json_jiexi(int displayinfo) {
  StaticJsonDocument<128> doc;

  DeserializationError error = deserializeJson(doc, json, MAX_INPUT_LENGTH);

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }

  JsonObject results_0 = doc["results"][0];

  JsonObject results_0_location = results_0["location"];
  const char* results_0_location_id = results_0_location["id"];  // "WTW3SJ5ZBJUY"
  // Serial.println(results_0_location_id);
  const char* results_0_location_name = results_0_location["name"];  // "Shanghai"
  // Serial.println(results_0_location_name);
  const char* results_0_location_country = results_0_location["country"];  // "CN"
  // Serial.println(results_0_location_country);
  const char* results_0_location_path = results_0_location["path"];  // "Shanghai,Shanghai,China"
  // Serial.println(results_0_location_path);
  const char* results_0_location_timezone = results_0_location["timezone"];  // "Asia/Shanghai"
  // Serial.println(results_0_location_timezone);
  const char* results_0_location_timezone_offset = results_0_location["timezone_offset"];  // "+08:00"
  // Serial.println(results_0_location_timezone_offset);

  JsonObject results_0_now = results_0["now"];
  char* results_0_now_text = results_0_now["text"];  // "Clear"
  // Serial.println(results_0_now_text);
  char* results_0_now_code = results_0_now["code"];  // "1"
  // Serial.println(results_0_now_code);
  char* results_0_now_temperature = results_0_now["temperature"];  // "25"
  // Serial.println(results_0_now_temperature);
  char* results_0_last_update = results_0["last_update"];  // "2023-09-29T22:50:14+08:00"
  // Serial.println(results_0_last_update);

  switch (displayinfo)
  {
  case 1:
    Serial.println(results_0_now_text);
    break;
  case 2:
    Serial.println(results_0_location_path);
    break;
  case 3:
    Serial.println(results_0_location_timezone);
    break;
  case 4:
    Serial.println(results_0_now_temperature);
    break;
  
  default:
    break;
  }
}

void Get_info(SoftwareSerial& mySerial,int displayinfo)
{
  // mySerial.println("GET https://api.seniverse.com/v3/weather/now.json?key=S0GQwFP0zq1hqTbSq&location=Suzhou&language=en&unit=c");  //开始透传
  // mySerial.println("Sending");
  // delay(1000);
  while (!mySerial.available())
    ;
  // Reiceve();
  int i = 0;
  while (mySerial.available())  //获取从软串口读取有效的字节数
  {
    json[i++] = mySerial.read();
    delay(1);
  }
  // Serial.println(json);
  // delay(200);
  json_jiexi(displayinfo);
  delay(1000);
}

